import axios from 'axios';

export async function uploadToDouyinAPI(data: any) {
  try {
    console.log('抖音API请求数据:', JSON.stringify(data));
    const response = await axios.post('/douyin-api/api/v1/command', data, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
      }
    });

    console.log('抖音API响应状态:', response.status);
    console.log('抖音API响应数据:', JSON.stringify(response.data));

    if (response.status !== 200) {
      throw new Error(`请求失败，状态码: ${response.status}，响应: ${JSON.stringify(response.data)}`);
    }

    if (!response.data) {
      throw new Error('API返回空数据');
    }

    // 调整成功条件判断，适应API实际返回格式
    // API返回格式: {"status":"success","code":200,"taskId":"..."}
    if (response.data.status !== 'success' || response.data.code !== 200) {
      throw new Error(`API返回错误: ${response.data.message || response.data.error || '未知错误'}，完整响应: ${JSON.stringify(response.data)}`);
    }

    // 提取taskId并返回
    return {
      success: true,
      taskId: response.data.taskId,
      data: response.data
    };
  } catch (error) {
    console.error('上传到抖音失败: ', error);
    if (error instanceof Error) {
      if (error.message.includes('403')) {
        throw new Error('抖音发布失败: 权限不足，请检查认证信息');
      } else if (error.message.includes('Invalid URL')) {
        throw new Error('抖音发布失败: URL格式无效，请检查视频和封面URL');
      } else if (error.message.includes('ECONNREFUSED')) {
        throw new Error('抖音发布失败: 无法连接到API服务，请检查服务是否运行');
      }
    }
    throw error;
  }
}